import {WORKSTATE, workSwitch} from "./public/CreepPublicAction.js";

export const harvesterMineralRun = (creep) => {
    workSwitch(creep, RESOURCE_ZYNTHIUM)
    if (creep.memory[WORKSTATE]) {
        workCore(creep)
    } else {
        getSources(creep)
    }
}

const workCore = (creep) => {
    /**
     * 矿物
     * @type {Mineral}
     */
    const mineral = Game.getObjectById(Memory.Rooms[creep.room.name].mineral)
    const factory = Game.rooms[creep.room.name].find(FIND_STRUCTURES, {filter: {structureType: STRUCTURE_FACTORY}})
    if (factory.length > 0) {
        if (creep.transfer(factory[0], mineral.mineralType) === ERR_NOT_IN_RANGE) {
            creep.moveTo(factory[0]);
        }
    } else {
        const terminal = creep.room.terminal
        if (creep.transfer(terminal, mineral.mineralType) === ERR_NOT_IN_RANGE) {
            creep.moveTo(terminal);
        }
    }
}

const getSources = (creep) => {
    /**
     * 矿物
     * @type {Mineral}
     */
    const mineral = Game.getObjectById(Memory.Rooms[creep.room.name].mineral)
    if (mineral.mineralAmount === 0) {
        const terminal = creep.room.terminal
        const storage = creep.room.storage
        if (terminal.store[mineral.mineralType] > 0 || storage.store[mineral.mineralType] > 0) {
            if (creep.withdraw(terminal, mineral.mineralType) === ERR_NOT_IN_RANGE) {
                creep.moveTo(terminal);
            }
        }
    } else {
        if (creep.harvest(mineral) === ERR_NOT_IN_RANGE) {
            creep.moveTo(mineral);
        }
    }
}